"""
配置验证服务
"""
from typing import Dict, Any, List, Optional
from pydantic import BaseModel, ValidationError
import structlog

logger = structlog.get_logger(__name__)


class ValidationResult(BaseModel):
    """验证结果"""
    valid: bool
    errors: List[str] = []
    warnings: List[str] = []
    suggestions: List[str] = []


class ConfigValidationService:
    """配置验证服务"""
    
    def __init__(self):
        self.validation_rules = self._init_validation_rules()
    
    def _init_validation_rules(self) -> Dict[str, Dict[str, Any]]:
        """初始化验证规则"""
        return {
            "STREAM_PROCESSING_WORKERS": {
                "type": int,
                "min": 1,
                "max": 50,
                "description": "流处理工作进程数"
            },
            "CAMERAS_PER_WORKER": {
                "type": int,
                "min": 1,
                "max": 200,
                "description": "每个工作进程处理的摄像头数量"
            },
            "VIDEO_PROCESSING_FPS": {
                "type": int,
                "min": 1,
                "max": 30,
                "description": "视频处理帧率"
            },
            "MAX_PROCESSING_LATENCY": {
                "type": (int, float),
                "min": 0.1,
                "max": 10.0,
                "description": "最大处理延迟(秒)"
            },
            "STREAM_HEALTH_CHECK_INTERVAL": {
                "type": int,
                "min": 5,
                "max": 300,
                "description": "流健康检查间隔(秒)"
            },
            "STREAM_RESTART_COOLDOWN": {
                "type": int,
                "min": 10,
                "max": 600,
                "description": "流重启冷却时间(秒)"
            },
            "AI_BATCH_SIZE": {
                "type": int,
                "min": 1,
                "max": 64,
                "description": "AI批处理大小"
            },
            "AI_PROCESSING_TIMEOUT": {
                "type": (int, float),
                "min": 0.5,
                "max": 30.0,
                "description": "AI处理超时(秒)"
            },
            "METRICS_COLLECTION_INTERVAL": {
                "type": int,
                "min": 1,
                "max": 300,
                "description": "指标收集间隔(秒)"
            },
            "PERFORMANCE_REPORT_INTERVAL": {
                "type": int,
                "min": 60,
                "max": 3600,
                "description": "性能报告生成间隔(秒)"
            }
        }
    
    def validate_config_value(self, config_key: str, value: Any) -> ValidationResult:
        """验证单个配置值"""
        result = ValidationResult(valid=True)
        
        try:
            if config_key not in self.validation_rules:
                result.warnings.append(f"未知的配置项: {config_key}")
                return result
            
            rule = self.validation_rules[config_key]
            
            # 类型验证
            expected_type = rule["type"]
            if isinstance(expected_type, tuple):
                if not isinstance(value, expected_type):
                    result.valid = False
                    result.errors.append(f"{config_key} 类型错误，期望 {expected_type}，实际 {type(value)}")
                    return result
            else:
                if not isinstance(value, expected_type):
                    result.valid = False
                    result.errors.append(f"{config_key} 类型错误，期望 {expected_type.__name__}，实际 {type(value).__name__}")
                    return result
            
            # 范围验证
            if "min" in rule and value < rule["min"]:
                result.valid = False
                result.errors.append(f"{config_key} 值过小，最小值为 {rule['min']}")
            
            if "max" in rule and value > rule["max"]:
                result.valid = False
                result.errors.append(f"{config_key} 值过大，最大值为 {rule['max']}")
            
            # 性能建议
            self._add_performance_suggestions(config_key, value, result)
            
        except Exception as e:
            result.valid = False
            result.errors.append(f"验证过程出错: {str(e)}")
        
        return result
    
    def _add_performance_suggestions(self, config_key: str, value: Any, result: ValidationResult):
        """添加性能建议"""
        if config_key == "STREAM_PROCESSING_WORKERS":
            if value > 20:
                result.suggestions.append("工作进程数过多可能导致资源竞争，建议根据CPU核心数调整")
        
        elif config_key == "CAMERAS_PER_WORKER":
            if value > 100:
                result.suggestions.append("每个工作进程处理过多摄像头可能影响性能")
        
        elif config_key == "VIDEO_PROCESSING_FPS":
            if value > 10:
                result.suggestions.append("高帧率处理会消耗更多CPU和GPU资源")
        
        elif config_key == "AI_BATCH_SIZE":
            if value > 32:
                result.suggestions.append("大批处理可能增加延迟，建议根据GPU内存调整")
        
        elif config_key == "STREAM_HEALTH_CHECK_INTERVAL":
            if value < 10:
                result.suggestions.append("过于频繁的健康检查可能影响性能")
    
    def validate_camera_ai_config(self, camera_id: str, ai_config: Dict[str, Any]) -> ValidationResult:
        """验证摄像头AI配置"""
        result = ValidationResult(valid=True)
        
        try:
            # 验证必需字段
            required_fields = ["enabled_algorithms", "processing_fps", "priority_level"]
            for field in required_fields:
                if field not in ai_config:
                    result.valid = False
                    result.errors.append(f"缺少必需字段: {field}")
            
            # 验证AI算法列表
            enabled_algorithms = ai_config.get("enabled_algorithms", [])
            if not isinstance(enabled_algorithms, list):
                result.valid = False
                result.errors.append("enabled_algorithms 必须是列表类型")
            else:
                available_algorithms = [
                    "behavior_analysis", "crowd_density", "waste_detection",
                    "cleanliness_assessment", "teaching_quality", "classroom_quality",
                    "conflict_detection", "pose_detection", "trajectory_analysis",
                    "lighting_detection", "energy_analysis"
                ]
                
                for algorithm in enabled_algorithms:
                    if algorithm not in available_algorithms:
                        result.valid = False
                        result.errors.append(f"未知的AI算法: {algorithm}")
                
                # 性能建议
                if len(enabled_algorithms) > 5:
                    result.warnings.append("启用过多AI算法可能影响处理性能")
                
                if len(enabled_algorithms) == 0:
                    result.warnings.append("未启用任何AI算法")
            
            # 验证处理帧率
            processing_fps = ai_config.get("processing_fps")
            if processing_fps is not None:
                if not isinstance(processing_fps, int) or not (1 <= processing_fps <= 30):
                    result.valid = False
                    result.errors.append("processing_fps 必须在1-30之间")
                elif processing_fps > 10:
                    result.suggestions.append("高帧率处理会消耗更多资源")
            
            # 验证优先级
            priority_level = ai_config.get("priority_level")
            if priority_level is not None:
                if not isinstance(priority_level, int) or not (1 <= priority_level <= 10):
                    result.valid = False
                    result.errors.append("priority_level 必须在1-10之间")
            
            # 验证自定义设置
            custom_settings = ai_config.get("custom_settings", {})
            if not isinstance(custom_settings, dict):
                result.valid = False
                result.errors.append("custom_settings 必须是字典类型")
            
        except Exception as e:
            result.valid = False
            result.errors.append(f"验证过程出错: {str(e)}")
        
        return result
    
    def validate_performance_thresholds(self, thresholds: Dict[str, float]) -> ValidationResult:
        """验证性能告警阈值"""
        result = ValidationResult(valid=True)
        
        try:
            required_thresholds = {
                "cpu_usage": (0.0, 100.0),
                "memory_usage": (0.0, 100.0),
                "gpu_usage": (0.0, 100.0),
                "processing_latency": (0.1, 30.0),
                "frame_drop_rate": (0.0, 100.0)
            }
            
            for threshold_name, (min_val, max_val) in required_thresholds.items():
                if threshold_name not in thresholds:
                    result.valid = False
                    result.errors.append(f"缺少告警阈值: {threshold_name}")
                    continue
                
                value = thresholds[threshold_name]
                if not isinstance(value, (int, float)):
                    result.valid = False
                    result.errors.append(f"{threshold_name} 必须是数值类型")
                    continue
                
                if not (min_val <= value <= max_val):
                    result.valid = False
                    result.errors.append(f"{threshold_name} 值必须在 {min_val}-{max_val} 之间")
                
                # 建议
                if threshold_name in ["cpu_usage", "memory_usage", "gpu_usage"]:
                    if value > 95:
                        result.suggestions.append(f"{threshold_name} 阈值过高，可能导致系统不稳定")
                    elif value < 50:
                        result.suggestions.append(f"{threshold_name} 阈值过低，可能产生过多告警")
        
        except Exception as e:
            result.valid = False
            result.errors.append(f"验证过程出错: {str(e)}")
        
        return result
    
    def validate_batch_config(self, configs: Dict[str, Any]) -> Dict[str, ValidationResult]:
        """批量验证配置"""
        results = {}
        
        for config_key, value in configs.items():
            results[config_key] = self.validate_config_value(config_key, value)
        
        return results
    
    def get_validation_rules_summary(self) -> Dict[str, Any]:
        """获取验证规则摘要"""
        summary = {}
        
        for config_key, rule in self.validation_rules.items():
            summary[config_key] = {
                "description": rule.get("description", ""),
                "type": rule["type"].__name__ if not isinstance(rule["type"], tuple) else [t.__name__ for t in rule["type"]],
                "range": f"{rule.get('min', 'N/A')} - {rule.get('max', 'N/A')}"
            }
        
        return summary


# 全局验证服务实例
validation_service = ConfigValidationService()


def get_validation_service() -> ConfigValidationService:
    """获取配置验证服务实例"""
    return validation_service